package leetcode

//https://leetcode.com/problems/add-two-numbers/


fun main(args: Array<String>) {
    val a = ListNode(2, ListNode(4, ListNode(3, null)))
    val b = ListNode(5, ListNode(6, ListNode(4, null)))
    var listNode = addTwoNumbers(a, b)
    print(listNode)
}

data class ListNode(var `val`: Int = 0, var next: ListNode? = null)


fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
    var carry = false
    var value = 0
    val header: ListNode? = ListNode(0, null)
    var next: ListNode? = header
    var aNext: ListNode? = l1
    var bNext: ListNode? = l2


    while (aNext != null || bNext != null || carry) {//可能最后一位是进位，需要额外一个节点
        value += if (aNext != null) aNext.`val` else 0
        value += if (bNext != null) bNext.`val` else 0
        if (carry)
            value++

        if (value >= 10) {
            value %= 10
            carry = true
        } else carry = false

        next!!.`val` = value
        if ((aNext != null && aNext.next != null) || (bNext != null && bNext.next != null) || carry)//此时只有最后的进位需要处理，此后退出while循环
        {
            next.next = ListNode()
            next = next.next
        }


        if (aNext != null)
            aNext = aNext.next
        if (bNext != null)
            bNext = bNext.next

        value = 0//reset
    }
    return header
}

